<script setup lang="ts">
import { onMounted, ref } from "vue";
import { ipcRenderer } from "electron";
import fs from "fs";
import path from "path";
import { useRouter } from "vue-router";

onMounted(() => {
  initNotification();
});
const router = useRouter();
const imgSrc = ref("");
const fileName = ref("");
const getFile = () => {
  console.log(fileName.value);
  fs.readFile(`file/${fileName.value}`, "base64", function (err, result) {
    //打印成功结果,如果读取失败
    if (err) {
      return console.log("文件读取失败" + err.message);
    }
    // console.log("文件读取成功", result);
    const img = new Image();
    img.src = `data:image/png;base64,${result}`;
    img.onload = function () {
      imgSrc.value = img.src;
    };
    // const blob = new Blob([result], { type: "image/png" });
    // const fileReader = new FileReader();
    // fileReader.readAsDataURL(blob);
    // fileReader.onload = function (e) {
    //   console.log("fileReader", e.target.result);
    //   // imgSrc.value = e.target.result;
    //   const img = new Image();
    //   img.src = e.target.result;
    //   img.onload = function () {
    //     imgSrc.value = img.src;
    //   };
    // };
  });
};
const saveFile = (e) => {
  // console.log(fs);
  console.log(e.target.files[0]);
  const file = e.target.files[0];
  const buffer = fs.readFileSync(file.path);
  fs.writeFile(`file/${file.name}`, buffer, (err) => {
    if (err) {
      alert("文件保存失败！");
    } else {
      alert("文件保存成功！");
      fileName.value = file.name;
    }
  });
};
const send = (msg) => {
  //渲染信息给主线程发送消息
  ipcRenderer.send("message", msg);
};
const openNewWindow = () => {
  window.open("https://www.baidu.com", "_blank");
};
const initNotification = () => {
  Notification.requestPermission().then((result) => {
    if (result === "granted") {
      const notification = new Notification("Electron Vite", {
        body: "Hello, World!",
        icon: "./assets/electron-vite.png",
      });
    }
  });
};
const showCallNotification = () => {
  let obj = {
    width: screen.width,
    height: screen.height,
  };
  ipcRenderer.send("create-notification", obj);
  // const notification = new Notification("来电提醒", {
  //   body: "有人打电话给你",
  //   icon: "./assets/electron-vite.png",
  // })
  // notification.onclick = () => {
  //   console.log("notification clicked")
  // }
};
const goWebView = () => {
  router.push("/webViewTest");
};
const goChat = () => {
  router.push("/chatRoom");
}
</script>

<template>
  <div>我是首页</div>
  <hr />
  <button @click="openNewWindow">打开新的窗体</button>
  <hr />
  <button @click="send('start')">图标闪烁</button>
  <button @click="send('stop')">图标停止闪烁</button>
  <hr />
  <button @click="showCallNotification">来电提示</button>
  <hr />
  <input type="file" @change="saveFile" />
  <button @click="getFile">获取本地图片</button>
  <img :src="imgSrc" alt="显示本地图片" />
  <hr />
  <button @click="goWebView">去webView测试页面</button>
  <hr />
  <button @click="goChat">去聊天页面</button>
</template>

<style scoped>
</style>
